<template>
  <a-form
      :model="ruleForm"
      ref="ruleForm"
      v-bind="layout"
      :rules="rules"
      @finish="handleFinish"
  >
    <a-form-item label="样品名称" name="sample_name">
      <a-input v-model:value="ruleForm.sample_name" />
    </a-form-item>
    <a-form-item label="合金代码" name="alloy_code">
      <a-select
        v-model:value="ruleForm.alloy_code"
        style="width: 120px"
        ref="select"
      >
        <a-select-option
          v-for="item in alloyCodeSelectionOptions"
          :key="item.url"
        >
          {{ item.label }}
        </a-select-option>
      </a-select>
    </a-form-item>
      <a-form-item label="数据来源" name="data_source">
        <a-input v-model:value="ruleForm.data_source"/>
      </a-form-item>
      <a-form-item label="样品状态" name="sample_status">
        <a-input v-model:value="ruleForm.sample_status"/>
      </a-form-item>
      <a-form-item label="设备名称" name="equipment_name">
        <a-input v-model:value="ruleForm.equipment_name"/>
      </a-form-item>
      <a-form-item label="设备厂家" name="equipment_manufacturer">
        <a-input v-model:value="ruleForm.equipment_manufacturer"/>
      </a-form-item>
      <a-form-item label="设备型号" name="device_model">
        <a-input v-model:value="ruleForm.device_model"/>
      </a-form-item>
      <a-form-item label="载荷" name="load">
        <a-input v-model:value="ruleForm.load"/>
      </a-form-item>
      <a-form-item label="拉伸速率" name="stretching_rate">
        <a-input v-model:value="ruleForm.stretching_rate"/>
      </a-form-item>
      <a-form-item label="应变速率" name="strain_rate">
        <a-input v-model:value="ruleForm.strain_rate"/>
      </a-form-item>
      <a-form-item label="样品标距" name="sample_range">
        <a-input v-model:value="ruleForm.sample_range"/>
      </a-form-item>
      <a-form-item label="样品厚度" name="sample_thickness">
        <a-input v-model:value="ruleForm.sample_thickness"/>
      </a-form-item>
      <a-form-item label="样品宽度" name="sample_width">
        <a-input v-model:value="ruleForm.sample_width"/>
      </a-form-item>
      <a-form-item label="测试温度" name="test_temperature">
        <a-input v-model:value="ruleForm.test_temperature"/>
      </a-form-item>
      <a-form-item label="杨氏模量" name="young_modulus">
        <a-input v-model:value="ruleForm.young_modulus"/>
      </a-form-item>
      <a-form-item label="屈服强度" name="yield_strength">
        <a-input v-model:value="ruleForm.yield_strength"/>
      </a-form-item>
      <a-form-item label="上屈服强度" name="up_yield_strength">
        <a-input v-model:value="ruleForm.up_yield_strength"/>
      </a-form-item>
      <a-form-item label="下屈服强度" name="down_yield_strength">
        <a-input v-model:value="ruleForm.down_yield_strength"/>
      </a-form-item>
      <a-form-item label="极限抗拉强度" name="ultimate_tensile_strength">
        <a-input v-model:value="ruleForm.ultimate_tensile_strength"/>
      </a-form-item>
      <a-form-item label="断裂强度" name="fracture_strength">
        <a-input v-model:value="ruleForm.fracture_strength"/>
      </a-form-item>
      <a-form-item label="断后延伸率" name="break_elongation">
        <a-input v-model:value="ruleForm.break_elongation"/>
      </a-form-item>
      <a-form-item label="断面收缩率" name="section_reduction">
        <a-input v-model:value="ruleForm.section_reduction"/>
      </a-form-item>
        <a-form-item label="均匀延伸率" name="uniform_elongation">
        <a-input v-model:value="ruleForm.uniform_elongation"/>
      </a-form-item>
      <a-form-item label="真应力" name="true_stress">
        <a-input v-model:value="ruleForm.true_stress"/>
      </a-form-item>
      <a-form-item label="真应变" name="true_strain">
        <a-input v-model:value="ruleForm.true_strain"/>
      </a-form-item>
      <a-form-item label="加工硬化速率" name="work_hardening_rate">
        <a-input v-model:value="ruleForm.work_hardening_rate"/>
      </a-form-item>
      <a-form-item label="工程应力-应变曲线" name="engineering_stress_strain" style="width: 1000px">
        <a-upload
            :fileList="ruleForm.engineering_stress_strainFileList"
            :beforeUpload="beforeEngineering_stress_strainUpload"
            :headers="headers"
            @change="handleengineering_stress_strainChange">
          <a-button>
            <upload-outlined/>
            选择
          </a-button>
        </a-upload>
      </a-form-item>
      <a-form-item label="真应力-应变曲线" name="true_stress_strain" style="width: 1000px">
        <a-upload
            :fileList="ruleForm.true_stress_strainFileList"
            :beforeUpload="beforetrue_stress_strainUpload"
            :headers="headers"
            @change="handletrue_stress_strainChange">
          <a-button>
            <upload-outlined/>
            选择
          </a-button>
        </a-upload>
      </a-form-item>
    <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
      <a-button type="primary" :loading="submitting" html-type="submit">
        {{ submitting ? '提交中' : '确定' }}
      </a-button>
    </a-form-item>
  </a-form>
</template>
<script>
import { message } from 'ant-design-vue'
import { UploadOutlined } from '@ant-design/icons-vue'

export default {
  name: 'AddOrEditTensileMechanicalProperty',
  // url !== ''则为编辑操作，否则为添加
  props: ['url'],
  emits: ['operate-success', 'operate-failed'],
  components: {
    UploadOutlined,
  },
  data() {
    // sample_range: ["该字段不能为空。"]
    // sample_thickness: ["该字段不能为空。"]
    // sample_width: ["该字段不能为空。"]
    // strain_rate: ["该字段不能为空。"]
    // stretching_rate: ["该字段不能为空。"]
    // test_temperature: ["该字段不能为空。"]
    let validateSampleRange = async (rule, value) => {
      if (value === "") {
        return Promise.reject("请选择样品标距");
      }
    };
    let validateSampleThickness = async (rule, value) => {
      if (value === "") {
        return Promise.reject("请输入样品厚度");
      }
    };
    let validateSampleWidth = async (rule, value) => {
      if (value === "") {
        return Promise.reject("请选择样品宽度");
      }
    };
    let validateStrainRate = async (rule, value) => {
      if (value === "") {
        return Promise.reject("请选择应变速率");
      }
    };
    let validateStretchingRate = async (rule, value) => {
      if (value === "") {
        return Promise.reject("请输入拉伸速率");
      }
    };
    let validateTestTemperature = async (rule, value) => {
      if (value === "") {
        return Promise.reject("请输入测试温度");
      }
    }
    return {
      ruleForm: {
        sample_name: '',
        alloy_code: '',
        data_source:'',
        sample_status: '',
        equipment_name: '',
        equipment_manufacturer: '',
        device_model: '',
        load: '',
        stretching_rate: '',
        strain_rate: '',
        sample_range: '',
        sample_thickness: '',
        sample_width: '',
        test_temperature: '',
        young_modulus: '',
        yield_strength: '',
        up_yield_strength: '',
        down_yield_strength: '',
        ultimate_tensile_strength: '',
        fracture_strength: '',
        break_elongation: '',
        section_reduction: '',
        uniform_elongation: '',
        true_stress: '',
        true_strain: '',
        work_hardening_rate: '',
        engineering_stress_strainFileList:[],
        true_stress_strainFileList: [],
      },
      rules: {
        sample_range: [
          {
            validator: validateSampleRange,
            trigger: "change",
            required: true,
            whitespace: true,
          },
      ],
        sample_thickness: [
          {
            validator: validateSampleThickness,
            trigger: 'change',
            required: true,
            whitespace: true,
          },
        ],
        sample_width: [
          {
            validator: validateSampleWidth,
            trigger: 'change',
            required: true,
            whitespace: true,
          },
        ],
        strain_rate: [
          {
            validator: validateStrainRate,
            trigger: 'change',
            required: true,
            whitespace: true,
          },
        ],
        stretching_rate: [
          {
            validator: validateStretchingRate,
            trigger: 'change',
            required: true,
            whitespace: true,
          },
        ],
        test_temperature: [
          {
            validator: validateTestTemperature,
            trigger: 'change',
            required: true,
            whitespace: true,
          },
        ],
      },
      layout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 14 },
      },
      submitting: false,
      alloyCodeSelectionOptions: [],
      headers: {
        authorization: 'authorization-text',
      },
    }
  },
  mounted() {
    this.fetch()
  },
  methods: {
    // 从后端获取数据
    fetch() {
      this.alloyCodeSelectionOptions = []
      this.axios
        .get('/attachment_management/alloy_phase_diagram/')
        .then((res) => {
          const data = res.data
          for (let i = 0; i < data.length; ++i) {
            this.alloyCodeSelectionOptions.push({
              url: data[i].url,
              label: data[i].alloy_code,
            })
          }
          this.ruleForm.alloy_code = data.length === 0 ? '' : data[0].url
          if (this.url !== '') {
            this.axios
              .get(this.url)
              .then((res) => {
                const data = res.data
                this.ruleForm.sample_name = data.sample_name
                this.ruleForm.alloy_code = data.alloy_code
                this.ruleForm.data_source = data.data_source
                this.ruleForm.sample_status = data.sample_status
                this.ruleForm.equipment_name = data.equipment_name
                this.ruleForm.equipment_manufacturer = data.equipment_manufacturer
                this.ruleForm.device_model = data.device_model
                this.ruleForm.load = data.load
                this.ruleForm.stretching_rate = data.stretching_rate
                this.ruleForm.strain_rate = data.strain_rate
                this.ruleForm.sample_range = data.sample_range
                this.ruleForm.sample_thickness = data.sample_thickness
                this.ruleForm.sample_width = data.sample_width
                this.ruleForm.test_temperature = data.test_temperature
                this.ruleForm.young_modulus = data.young_modulus
                this.ruleForm.yield_strength = data.yield_strength
                this.ruleForm.up_yield_strength = data.up_yield_strength
                this.ruleForm.down_yield_strength = data.down_yield_strength
                this.ruleForm.ultimate_tensile_strength = data.ultimate_tensile_strength
                this.ruleForm.fracture_strength = data.fracture_strength
                this.ruleForm.break_elongation = data.break_elongation
                this.ruleForm.section_reduction = data.section_reduction
                this.ruleForm.uniform_elongation = data.uniform_elongation
                this.ruleForm.true_stress = data.true_stress
                this.ruleForm.true_strain = data.true_strain
                this.ruleForm.work_hardening_rate = data.work_hardening_rate
                if (data.engineering_stress_strain_filename !== '') {
                  // console.log('not null')
                  this.ruleForm.engineering_stress_strainFileList.push({
                    uid: '-1',
                    name: data.engineering_stress_strain_filename,
                  })
                }
                if (data.true_stress_strain_filename !== '') {
                  // console.log('not null')
                  this.ruleForm.true_stress_strainFileList.push({
                    uid: '-2',
                    name: data.true_stress_strain_filename,
                  })
                }
              })
              .catch((error) => {
                console.log('Error', error.message)
              })
          }
        })
        .catch((error) => {
          console.log('Error', error.message)
          this.ruleForm.alloy_code = ''
        })
    },
    // onChange(e) {
    //   console.log('radio checked', e.target.value)
    // },
    handleFinish(values) {
      this.submitting = true
      const {
        engineering_stress_strainFileList,
        true_stress_strainFileList,
      } = this.ruleForm
      const formData = new FormData()
      formData.append('sample_name', values.sample_name)
      formData.append('alloy_code', values.alloy_code)
      formData.append('data_source', values.data_source)
      formData.append('sample_status', values.sample_status)
      formData.append('equipment_name', values.equipment_name)
      formData.append('equipment_manufacturer', values.equipment_manufacturer)
      formData.append('load', values.load)
      formData.append('stretching_rate', values.stretching_rate)
      formData.append('strain_rate', values.strain_rate)
      formData.append('sample_range', values.sample_range)
      formData.append('sample_thickness', values.sample_thickness)
      formData.append('sample_width', values.sample_width)
      formData.append('test_temperature', values.test_temperature)
      formData.append('young_modulus', values.young_modulus)
      formData.append('yield_strength', values.yield_strength)
      formData.append('up_yield_strength', values.up_yield_strength)
      formData.append('down_yield_strength', values.down_yield_strength)
      formData.append('ultimate_tensile_strength', values.ultimate_tensile_strength)
      formData.append('fracture_strength', values.fracture_strength)
      formData.append('break_elongation', values.break_elongation)
      formData.append('section_reduction', values.section_reduction)
      formData.append('uniform_elongation', values.uniform_elongation)
      formData.append('true_stress', values.true_stress)
      formData.append('true_strain', values.true_strain)
      formData.append('work_hardening_rate', values.work_hardening_rate)
      engineering_stress_strainFileList.forEach((file) => {
        // console.log(file.originFileObj)
        if ('originFileObj' in file) {
          formData.append('engineering_stress_strain', file.originFileObj)
        }
      })
      true_stress_strainFileList.forEach((file) => {
        if ('originFileObj' in file) {
          // console.log(file.originFileObj)
          formData.append('true_stress_strain', file.originFileObj)
        }
      })
      if (this.url !== '') {
        if (this.ruleForm.engineering_stress_strainFileList.length === 0) {
          formData.append('engineering_stress_strain_empty', true)
        }
        if (this.ruleForm.true_stress_strainFileList.length === 0) {
          formData.append('true_stress_strain_empty', true)
        }
        this.axios
          .put(this.url, formData)
          .then(() => {
            this.submitting = false
            message.success('修改成功！')
            this.$emit('operate-success')
          })
          .catch((error) => {
            this.submitting = false
            message.error('修改失败！')
            this.$emit('operate-failed')
            console.log('Error', error.message)
          })
      } else {
        this.axios
          .post('/property_management/tensile_property/', formData)
          .then(() => {
            this.submitting = false
            message.success('添加成功！')
            this.$emit('operate-success')
          })
          .catch((error) => {
            this.submitting = false
            message.error('添加失败！')
            this.$emit('operate-failed')
            console.log('Error', error.message)
          })
      }
    },
   beforeEngineering_stress_strainUpload(file) {
      this.ruleForm.engineering_stress_strainFileList = [
        ...this.ruleForm.engineering_stress_strainFileList,
        file,
      ]
      return false
    },
    handleengineering_stress_strainChange(info) {
      let fileList = [...info.fileList]
      // 取最后选择的文件
      fileList = fileList.slice(-1)
      this.ruleForm.engineering_stress_strainFileList = fileList
    },
    beforetrue_stress_strainUpload(file) {
      this.ruleForm.true_stress_strainFileList = [
        ...this.ruleForm.true_stress_strainFileList,
        file,
      ]
      return false
    },
    handletrue_stress_strainChange(info) {
      let fileList = [...info.fileList]
      // 取最后选择的文件
      fileList = fileList.slice(-1)
      this.ruleForm.true_stress_strainFileList = fileList
    },
  },
}
</script>
